import os
import uuid

from django.db import models

# Create your models here.
from django.contrib.auth import get_user_model

# Create your models here.
User = get_user_model()


# Create your models here.
# Define user directory path
# 如果你不使用ModelForm，你还需要手动编写代码存储上传文件。 下面这个是使用 ModelForm 的东西.
def user_directory_path(instance, filename):
    """
    :param instance: 文件对象
    :param filename:
    :return:
    """
    ext = filename.split('.')[-1]
    filename = '{}.{}'.format(uuid.uuid4().hex[:10], ext)
    return os.path.join("users", filename)  # 'files/38c57709f8.png'


# https://www.it1352.com/1630128.html 参考
class Following(models.Model):
    target = models.ForeignKey("UserProfile", on_delete=models.CASCADE, verbose_name='被关注者', related_name='followers')
    follower = models.ForeignKey("UserProfile", on_delete=models.CASCADE, verbose_name='关注者', related_name='targets')
    follow_date = models.DateField(verbose_name='关注时间', auto_now=True)


class UserProfile(models.Model):
    user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='profile', verbose_name='档案所关联的用户')
    follows = models.ManyToManyField("UserProfile", through=Following, verbose_name="关注")
    GENDER_CHOICES = (
        ('M', '男'),
        ('F', '女'),
        ('U', '保密'),
    )
    nickname = models.CharField(blank=True, null=True, max_length=20, verbose_name='昵称', help_text='用户昵称')
    avatar = models.FileField(upload_to=user_directory_path, verbose_name='头像', help_text='用户头像', default='logo.jpg')
    mobile = models.CharField(blank=True, null=True, max_length=13, verbose_name='电话号码', help_text='请输入电话号码')
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True, verbose_name='性别',
                              help_text='性别')

    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = '全部用户信息'

    def __str__(self):
        return self.nickname
